package com.zhao.dota.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.dota.bo.PlayerMax;
import com.zhao.dota.common.contant.CommonConst;
import com.zhao.dota.contant.PerformanceFieldConst;
import com.zhao.dota.mapper.PerformanceMapper;
import com.zhao.dota.model.Performance;
import com.zhao.dota.model.Player;
import com.zhao.dota.service.PerformanceService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PerformanceServiceImpl extends ServiceImpl<PerformanceMapper, Performance> implements PerformanceService {


    @Override
    public int saveList(List<Performance> list) {
        int count = 0;
        for (Performance performance : list) {
            LambdaQueryWrapper<Performance> query = Wrappers.lambdaQuery(Performance.class)
                    .eq(Performance::getMatchId, performance.getMatchId())
                    .eq(Performance::getMatchPlayerId, performance.getMatchPlayerId());
            Performance old = getOne(query);
            if (old == null) {
                count += save(performance) ? 1 : 0;
            } else {
                BeanUtil.copyProperties(performance, old, CommonConst.IGNORE_NULL_VALUE);
                count += updateById(old) ? 1 : 0;
            }
        }
        return count;
    }

    @Override
    public List<Performance> findByMatchId(Integer matchId) {
        LambdaQueryWrapper<Performance> query = Wrappers.lambdaQuery(Performance.class)
                .eq(Performance::getMatchId, matchId);
        return list(query);
    }

    @Override
    public Performance countByPlayer(Player player, int limit) {
        return baseMapper.countByPlayer(player.getSteamId(), limit);
    }

    @Override
    public PlayerMax max(PerformanceFieldConst field, Long steamId) {
        return baseMapper.max(field.name(), steamId);
    }


}
